package com.learning.servlet2x.cookie;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;

/**
 * ClassName: CookieServlet
 * Description: Cookie 基础知识
 * Date: 2018/6/24 13:03 【需求编号】
 *
 * @author Sam Sho
 * @version V1.0.0
 */
public class CookieServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 1-创建Cookie
        String key = "key";
        String value = "cookie";
        Cookie cookie = new Cookie(key, value);
        System.out.println(cookie.getName());

        // 1-2 创建中文, 使用URLEncoder编码 和 URLDecoder解码
        Cookie cookieChina = new Cookie(URLEncoder.encode("中文", "UTF-8"), URLEncoder.encode("中文", "UTF-8"));
        System.out.println(cookieChina);


        // 3-从客户端获取
        Cookie[] cookies = req.getCookies();
        if (cookies != null && cookies.length < 0) {
            for (Cookie tCookie : cookies) {
                String tName = tCookie.getName();
                String tValue = tCookie.getValue();
                int maxAge = tCookie.getMaxAge();
                System.out.println("Cookie的name : " + tName + " | Cookie的value : " + tValue + " | Cookie的有效期:  " + maxAge);
            }
        }

        // 4-Cookie的删除与修改
        Cookie cookie2 = new Cookie("time", "201401008");
        // 删除Cookie,设置 setMaxAge =0 即可删除
        cookie2.setMaxAge(0);
        resp.addCookie(cookie2);
        // 使用同名Cookie, 修改前一个 cookie 的作用
        resp.addCookie(new Cookie("time", "20150909"));

        // 5-Cookie的域名
        Cookie cookie3 = new Cookie("time", "201401008");
        //设置域名，意思是所有 `baidu.com`下的二级域名都可以访问。必须以“.”开始
        cookie3.setDomain(".baidu.com");
        //设置所有路径都可以使用
        cookie3.setPath("/");
        //设置有效期
        cookie3.setMaxAge(Integer.MAX_VALUE);
        resp.addCookie(cookie3);
    }
}
